import { ref } from 'vue'
import { defineStore } from 'pinia'
import { modifyLastReadingChapter, getBookshelf } from '@/api/book'
import { ElMessage, dayjs } from 'element-plus'
import { getBookshelfDb } from '@/utils/localDb'
import bookContract from '@/contracts/db/bookshelfContract'

export const useBookshelfStore = defineStore('bookshelfStore', () => {
  const books = ref([]) // 书架
  const bookshelf = getBookshelfDb(bookContract.store)

  // 更新书籍最后阅读章节
  async function updateBookLastReadingCharpter(bookId, chapterId) {
    await getBooks()
    if (books.value.length > 0) {
      const currentBook = books.value.find((book) => {
        return book.bookId == bookId
      })
      if (currentBook) {
        const lastReadingDateTime = dayjs().format('YYYY-MM-DD HH:mm:ss')
        currentBook.lastReadingChapterId = chapterId
        currentBook.lastReadingDateTime = lastReadingDateTime
        bookshelf.setItem(bookContract.item.bookshelf, books.value)

        await modifyLastReadingChapter({ bookId, chapterId, lastReadingDateTime })
      }
    }
  }

  // 同步书架
  function syncBookshelf() {
    if (!navigator.onLine) {
      ElMessage.warning('请检查网络连接')
      return Promise.resolve([])
    }
    return getBookshelf()
      .then((apiRes) => {
        let serverBooks = apiRes.data // 服务器的书架内容
        books.value = serverBooks // 更新本地书架
        return Promise.resolve(serverBooks)
      })
      .catch((error) => {
        console.error('Error fetching bookshelf:', error)
        ElMessage.error('获取书架失败，请稍后重试')
      })
  }

  // 获取书架
  function getBooks() {
    return bookshelf.getItem(bookContract.item.bookshelf).then((bookshelfList) => {
      if (bookshelfList && bookshelfList.length > 0) {
        books.value = bookshelfList
        return Promise.resolve(books.value)
      } else {
        return syncBookshelf().then((data) => {
          bookshelf.setItem(bookContract.item.bookshelf, data)
          return Promise.resolve(data)
        })
      }
    })
  }

  // 获取指定书籍
  async function getBook(bookId) {
    await getBooks()
    const currentBook = books.value.find((book) => {
      return book.bookId == bookId
    })

    return currentBook
  }

  return { getBooks, getBook, updateBookLastReadingCharpter, syncBookshelf }
})
